package com.maxd.service.selfAliPay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.maxd.constants.AliPayConstants;
import com.maxd.error.ResultUtil;
import com.maxd.model.CashOut;
import com.maxd.model.CommonInfo;
import com.maxd.model.Orders;
import com.maxd.model.UserInfo;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfOrder.OrdersJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.HttpClientUtil;
import com.yungouos.pay.util.PaySignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SelfAliPayServiceImpl implements SelfAliPayService{
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean refund(Long ordersId) {
        CommonInfo commonInfo = commonRepository.findOne(87);
        Orders orders = ordersJpaRepository.getOne(ordersId);
        if("1".equals(commonInfo.getValue())){
            try {
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                AlipayTradeRefundModel model = new AlipayTradeRefundModel();
                model.setOutTradeNo(orders.getOrderNum()); //订单号
                model.setRefundAmount(orders.getPayMoney()+""); //退款金额
                request.setBizModel(model);
                AlipayTradeRefundResponse response = alipayClient.execute(request);
                if(response.isSuccess()){
                    return true;
                } else {
                    return false;
                }
            }catch (AlipayApiException e) {
                e.printStackTrace();
                log.error("秘钥退款异常:" + e.getMessage());
            }
        }else if("2".equals(commonInfo.getValue())){
            UserInfo userById = userRepository.getUserById(orders.getUserId());
            String url="https://api.pay.yungouos.com/api/finance/repay/alipay";
            Map<String,String> map=new HashMap<>();
            CommonInfo merchantId = commonRepository.findOne(235);
            CommonInfo password = commonRepository.findOne(236);
            map.put("merchant_id",merchantId.getValue());//YunGouOS商户ID。登录YunGouOS.com-》账户设置-》开发者身份-》账户商户号；
            map.put("out_trade_no",orders.getOrderNum());
            map.put("account",userById.getZhifubao());
            map.put("account_name",userById.getZhifubaoName());
            map.put("money",orders.getPayMoney()+"");
            map.put("desc",commonRepository.findOne(12).getValue() + "佣金结算");
            Map<String,Object> maps=new HashMap<>();
            maps.put("merchant_id",merchantId.getValue());
            maps.put("out_trade_no",orders.getOrderNum());
            maps.put("account",userById.getZhifubao());
            maps.put("account_name",userById.getZhifubaoName());
            maps.put("money",orders.getPayMoney());
            maps.put("desc",commonRepository.findOne(12).getValue() + "佣金结算");
            map.put("sign", PaySignUtil.createSign(maps,password.getValue()));
            String s = HttpClientUtil.doPost(url, map);
            JSONObject jsonObject = JSON.parseObject(s);
            String code = jsonObject.getString("code");
            if("1".equals(code)){
                JSONObject data = jsonObject.getJSONObject("data");
                String status = data.getString("status");
                if("1".equals(status)){
                    return true;
                }else{
                    log.error("退款失败！"+data.getString("reason"));
                    return false;
                }
            }else{
                log.error("yungouos:"+s);
                return false;
            }
        }else if("3".equals(commonInfo.getValue())){
            try {
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");  //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
                certAlipayRequest.setAppId(commonRepository.findOne(170).getValue());  //APPID 即创建应用后生成,详情见创建应用并获取 APPID
                certAlipayRequest.setPrivateKey(commonRepository.findOne(171).getValue());  //开发者应用私钥，由开发者自己生成
                certAlipayRequest.setFormat("json");  //参数返回格式，只支持 json 格式
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);  //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);  //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。

                CommonInfo url = commonRepository.findOne(200);
                certAlipayRequest.setCertPath(url.getValue()+"/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(url.getValue()+"/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(url.getValue()+"/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）

                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
                AlipayTradeRefundModel model = new AlipayTradeRefundModel();
                model.setOutTradeNo(orders.getOrderNum()); //订单号
                model.setRefundAmount(orders.getPayMoney()+""); //退款金额
                request.setBizModel(model);
                AlipayTradeRefundResponse response = alipayClient.execute(request);
                if(response.isSuccess()){
                    return true;
                } else {
                    return false;
                }
            } catch (AlipayApiException e) {
                log.error("证书退款异常:" + e.getMessage());
                e.printStackTrace();
            }
        }else{
            return true;
        }
        return false;
    }
}
